package org.jeecg.modules.door.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Component;


import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.cert.X509Certificate;

import static com.alibaba.druid.util.Utils.md5;

@Component
@Slf4j
public class AbutmentController {





        String csurl = "http://t.server.hxjiot.com/";
        String username = "sun";
        String password = "wodemensuo521";
        //http://t.server.hxjiot.com/apartmentLogin?accountName=sun&password=47D06B72C213593300F940BF32EA240D
        //从第三方获取门锁
        public  String Authentication(){
            try {
                String url;

              /*  url = csurl+"apartmentLogin?accountName="+username+"&password="+md5(password);
               */
                //这个是测试版本的，回头部署私服用上面注释的那个，上面目前密码错误
                url="http://t.server.hxjiot.com/apartmentLogin?accountName=sun&password=47D06B72C213593300F940BF32EA240D";
                System.out.println("url:"+url);
                CloseableHttpClient httpclient = createHttpClientWithNoSsl();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                String res = readResponse(response);
                String token="";
                if (StringUtils.isNotEmpty(res)) {
                    JSONObject jsonObject = JSON.parseObject(res);
                    System.out.println("json:"+jsonObject);
                    JSONObject data = jsonObject.getJSONObject("data");
                    token = data.getString("tokenId");//被识别人id
                    System.out.println("token:"+token);
                    return token;
                }
                return "";
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "";
        }


        //查询房间列表
    public String openSmartRoomList(String method,String tokenId,String startNum,String pageSize){
            try {
                String url;

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("method", method);
                jsonObject.put("tokenId", tokenId);
                JSONObject addressObject = new JSONObject();
                addressObject.put("startNum",startNum);
                addressObject.put("getNum",pageSize);
                jsonObject.put("data", addressObject);
                url = csurl + "openSmartRoomList?accountName=" + username + "&password=" + md5(password);
                System.out.println("url:" + url);
                CloseableHttpClient httpclient = createHttpClientWithNoSsl();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                String res = readResponse(response);
                return res;
            }catch (Exception e) {
                e.printStackTrace();
            }
        return "";

    }


    /**
     * 读取 response body 内容为字符串
     *
     * @return
     * @throws IOException
     */
    private static String readResponse(HttpResponse response) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String result = new String();
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        return result;
    }

    /**
     * 创建模拟客户端（针对 https 客户端禁用 SSL 验证）

     * @return
     * @throws Exception
     */
    private static CloseableHttpClient createHttpClientWithNoSsl() throws Exception {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        // don't check
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        // don't check
                    }
                }
        };

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, trustAllCerts, null);
        LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx);
        return HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .build();
    }
}
